from django.utils import simplejson
from google.appengine.ext import webapp, db

class RPCHandler(webapp.RequestHandler):
    """ Allows the functions defined in the RPCMethods class to be RPCed."""
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()
     
    def post(self):
        args = simplejson.loads(self.request.body)
        func, args = args[0], args[1:]
       
        if func[0] == '_':
            self.error(403) # access denied
            return
         
        func = getattr(self.methods, func, None)
        if not func:
            self.error(404) # file not found
            return
    
        result = func(*args)
        self.response.out.write(simplejson.dumps(result))

class RPCMethods:
    """ Defines the methods that can be RPCed.
        NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """

    def Add(self, *args):
        # The JSON encoding may have encoded integers as strings.
        # Be sure to convert args to any mandatory type(s).
        #ints = [int(arg) for arg in args]
        # return sum(ints)
        UserStats = db.GqlQuery("SELECT * FROM UserStat WHERE username = :1 LIMIT 10 ", str(args[0]))
        return UserStats[0].count

